package com.cy.server.controller;

import com.cy.server.pojo.Admin;
import com.cy.server.pojo.ChatMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;

/**
 * @peoject: yeb
 * @description: websocket
 * @author: LiShaoZhuo
 * @create: 2021-05-10 16:02
 **/
@Controller
public class WSController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/ws/chat")
    public void handleMsg(Authentication authentication, ChatMsg chatMsg){
        //获取用户
        Admin admin = (Admin) authentication.getPrincipal();
        chatMsg.setFrom(admin.getUsername());
        //设置昵称
        chatMsg.setFromNickName(admin.getName());
        chatMsg.setDate(LocalDateTime.now());

        /**
        * @Description: 发送消息
        * @Param: [authentication, chatMsg]
         * 发送给谁   路径   消息
        * @return: void
        * @Author: LiShaoZhuo
        * @Date: 2021/5/10
        */
        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(), "/queue/chat", chatMsg);
    }
}
